package com.zhuhjay.service.system.wxmp.interceptor;

import com.zhuhjay.common.base.model.domain.LimiterDetail;
import com.zhuhjay.common.core.helper.ApiLimiterHelper;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageInterceptor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ZhuHJay
 * @date 2023/8/4 19:30
 */
@Component
public class MessageLimiterInterceptor implements WxMpMessageInterceptor {

    @Resource
    private ApiLimiterHelper apiLimiterHelper;

    @Override
    public boolean intercept(
            WxMpXmlMessage wxMessage, Map<String, Object> context,
            WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {

        String openId = wxMessage.getFromUser();
        LimiterDetail limiterDetail = LimiterDetail.of(openId, null);
        limiterDetail.setLimit(10);
        limiterDetail.setMessage("您的操作过于频繁，请稍后再试");
        apiLimiterHelper.limiter(wxMessage.getMsgType(), limiterDetail, "公众号消息发送过于频繁");
        return true;
    }

}
